package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.dao.ArticleRepository;
import com.example.demo.domain.EsArticle;
import com.uubee.share.util.DateUtil;
import com.uubee.share.util.UuidUtil;
import com.uubee.share.wrapper.ModelListResult;
import com.zeus.media.dubbo.domain.ZeusArticle;
import com.zeus.media.dubbo.service.article.IZeusArticleService;

/**
 * <a href="http://47.94.197.1:9200/">es服务</a>
 * Created by wengjunjie on 2018/2/7.
 */
@RestController
@RequestMapping("article")
public class ArticleController {
    private static Logger logger = LoggerFactory.getLogger(ArticleController.class);
    @Autowired
    private IZeusArticleService zeusArticleService;
    @Autowired
    private ArticleRepository articleRepository;

    @RequestMapping("sync")
    public String syncArticle(ZeusArticle zeusArticle) {
        zeusArticle.setCorrelationID(UuidUtil.getUuid());
        ModelListResult<ZeusArticle> articleModelListResult = zeusArticleService.queryArticleListPage(zeusArticle);
        for (ZeusArticle article : articleModelListResult.getModel()) {
            EsArticle es = articleRepository.findById(article.getArticle_id());
            if (es != null) {
                continue;
            }
            logger.info("当前文章id={},es不存在,准备写入es", article.getArticle_id());
            EsArticle esArticle = dataFromArticle(article);
            articleRepository.save(esArticle);
        }
        return "sync ok";
    }

    @RequestMapping("delete")
    public String delete() {
        articleRepository.deleteAll();
        return "delete ok";
    }

    private EsArticle dataFromArticle(ZeusArticle article) {
        EsArticle es = new EsArticle();
        es.setId(article.getArticle_id());
        es.setAuthor(article.getArticle_author());
        es.setCreate_time(DateUtil.getDate(article.getDt_create()));
        es.setDesc(article.getArticle_desc());
        es.setKeywords(article.getArticle_keywords());
        es.setArticle_tag(article.getArticle_tag());
        es.setTitle(article.getArticle_title());
        return es;
    }
}
